#include <iostream>
#include <thread>
#include <boost/filesystem.hpp>
#include "loghelper.h"
#include "master_manager.h"
#include "json_message_processor.h"
#include "messagehandler.h"
#include "zmq_messenger.h"
#include "common.h"
#include "utility.hpp"
#include "messagebus.h"
using namespace boost;
using namespace RockLog;

MasterManager::MasterManager(AppConfig_t &cfg) : m_cfg(cfg)
{
}

MasterManager::~MasterManager()
{
}

void MasterManager::init()
{
    for (auto index = 0; index < this->m_cfg.processNum; ++index)
    {
        std::thread([index]() {
            std::string workerId = generateWorkerId(index); // TODO 考虑包括全局id对应关系
            // 订阅worker消息，create zmq subcribe
            subcribeMsg(workerId);
            }).detach();
    }

    MessageHandler::instance().init(m_cfg);
    g_messagebus.attach<const char *, const char *, uint32_t>(kZmqRecvMSG, &MessageHandler::onRecvMsg, MessageHandler::instance());
    startCheckInputConfigStatus();
}


void MasterManager::checkInputConfigStatus()
{
    if (m_inputLastWriteTime == 0)
    {
        m_inputLastWriteTime = boost::filesystem::last_write_time(m_cfg.inputConfigName.c_str());
    }
    else
    {
        if (m_inputLastWriteTime != boost::filesystem::last_write_time(m_cfg.inputConfigName.c_str()))
        {
            LOG(kInfo) << m_cfg.inputConfigName << "changed !!" << m_cfg.processName << "again.";
            loadInputConfig();
        }
    }
}

void MasterManager::startCheckInputConfigStatus()
{
    LOG(kInfo) << "[startCheckInputConfigStatus] start";
    std::thread([this](){
        while (true)
        {
            Utility::sleep(this->m_cfg.checkProcessInterval);
            this->checkInputConfigStatus();
            LOG(kDebug) << "[startCheckInputConfigStatus] checking...";
        }
    }).detach();
}

JsonMessageProcessor s_processor;
void MasterManager::loadInputConfig()
{
    std::string inputFileName = m_cfg.inputConfigName;
    if (inputFileName.empty())
    {
        return;
    }
    bool exist = true;
    if (!boost::filesystem::exists(inputFileName))
    {
        inputFileName = boost::filesystem::current_path().string() + "/" + inputFileName;
        if (!boost::filesystem::exists(inputFileName))
        {
            exist = false;
        }
        else
        {
            exist = true;
        }
    }

    if (exist)
    {
        LOG(kInfo) << "inputFileName: " << inputFileName;
        std::vector<CameraInfo_t> vec;
        s_processor.decodeCameraInfo(inputFileName, vec);

        for (size_t i = 0; i < vec.size(); i++)
        {
            CameraInfo_t &info = vec[i];
            std::string workerId = generateWorkerId(i);
            // 发布消息
            MessageHandler::instance().sendMsg(workerId, info);
            LOG(kInfo) << "[loadInputConfig] workerId:" << workerId << "publish a message";
        }
    }
    else
    {
        LOG(kErr) << "inputFileName: " << inputFileName << " not exist!";
    }
}
